package org.example.ychdp.controller;

import jakarta.servlet.http.HttpSession;
import org.example.ychdp.entity.User;
import org.example.ychdp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class userController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "personal")
    public String personal(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            String errorMsg = "您未登录，请登录";
            model.addAttribute("errorMsg",errorMsg);
            return "login";
        }
        model.addAttribute("user", user);
        return "personal";
    }

    @RequestMapping(value = "edit")
    public String editUser(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "editUser";
    }

    @RequestMapping("/update")
    public String updateUser(@ModelAttribute User user, @RequestParam("newPassword")String newPassword ,HttpSession session, Model model) {
        if (newPassword!=null){
            user.setPassword(newPassword);  // 新密码不为空时才修改
        }
        int success = userService.update(user);

        if (success != 0) {
            session.setAttribute("user", user); // 更新 session 中的用户信息
            model.addAttribute("message", "信息更新成功！");
            return "redirect:/personal";
        } else {
            model.addAttribute("message", "信息更新失败，请重试！");
            return "redirect:/edit";
        }
    }
}
